from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from typing import Dict, Any, Optional
from models.llm_models import RAGModel
from rag.rag_system import RAGSystem
from monitoring.decorators import monitor_api_endpoint
import logging

logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter()

# 请求和响应模型
class CodeReviewRequest(BaseModel):
    git_diff: str
    collection_name: Optional[str] = "default"
    use_rag: Optional[bool] = True
    session_id: Optional[str] = None
    user_id: Optional[str] = None

class CodeReviewResponse(BaseModel):
    passed: bool
    reason: str
    commitMessage: str
    optimizationSuggestion: str

@router.post("/check", response_model=CodeReviewResponse)
@monitor_api_endpoint("code_review_check")
async def check_code_standards(
    request: CodeReviewRequest,
    user_id: Optional[str] = Query(None, description="用户ID，用于追踪（URL参数）"),
    session_id: Optional[str] = Query(None, description="会话ID，用于追踪（URL参数）")
):
    """代码规范检查"""
    try:
        logger.info(f"收到代码规范检查请求，diff长度: {len(request.git_diff)}")
        
        # 优先使用请求体中的参数，如果没有则使用URL参数
        final_user_id = request.user_id or user_id
        final_session_id = request.session_id or session_id
        
        logger.info(f"追踪参数 - user_id: {final_user_id}, session_id: {final_session_id}")
    
        # 创建RAG模型，传递追踪参数
        rag_model = RAGModel()
        
        # 如果启用RAG，创建RAG系统用于检索规范文档
        rag_system = None
        search_keywords = ""
        if request.use_rag:
            try:
                rag_system = RAGSystem()
                logger.info("RAG系统已初始化，将检索相关规范文档")
                
                # 提取检索关键词，传递追踪参数
                search_keywords = rag_model._extract_search_keywords(
                    request.git_diff,
                    user_id=final_user_id,
                    session_id=final_session_id
                )
                logger.info(f"提取的检索关键词: {search_keywords}")
                
            except Exception as e:
                logger.warning(f"RAG系统初始化失败: {str(e)}，将使用默认检查")
        
        # 执行代码规范检查，传递追踪参数
        result = rag_model.check_code_standards(
            git_diff=request.git_diff,
            rag_system=rag_system,
            user_id=final_user_id,
            session_id=final_session_id
        )
        
        # 直接返回LLM的原始输出
        response = CodeReviewResponse(
            passed=result.get("pass", False),
            reason=result.get("reason", ""),
            commitMessage=result.get("commitMessage", ""),
            optimizationSuggestion=result.get("optimizationSuggestion", "")
        )
        
        logger.info(f"代码规范检查完成，结果: {'通过' if response.passed else '不通过'}")
        return response
        
    except Exception as e:
        logger.error(f"代码规范检查失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"代码规范检查失败: {str(e)}")

@router.post("/check-simple")
@monitor_api_endpoint("code_review_check_simple")
async def check_code_standards_simple(
    request: CodeReviewRequest,
    user_id: Optional[str] = Query(None, description="用户ID，用于追踪（URL参数）"),
    session_id: Optional[str] = Query(None, description="会话ID，用于追踪（URL参数）")
):
    """简化的代码规范检查（不使用RAG）"""
    try:
        logger.info(f"收到简化代码规范检查请求，diff长度: {len(request.git_diff)}")
        
        # 优先使用请求体中的参数，如果没有则使用URL参数
        final_user_id = request.user_id or user_id
        final_session_id = request.session_id or session_id
        
        logger.info(f"追踪参数 - user_id: {final_user_id}, session_id: {final_session_id}")
        
        # 确保在创建RAG模型之前禁用Langfuse自动集成
        import os
        os.environ["LANGFUSE_OPENAI_INTEGRATION"] = "false"
        os.environ["LANGFUSE_AUTO_INSTRUMENT"] = "false"
        os.environ["OPENAI_LANGFUSE_PUBLIC_KEY"] = ""
        os.environ["OPENAI_LANGFUSE_SECRET_KEY"] = ""
        os.environ["OPENAI_LANGFUSE_HOST"] = ""
        
        # 创建RAG模型
        rag_model = RAGModel()
        
        # 执行代码规范检查（不使用RAG检索），传递追踪参数
        result = rag_model.check_code_standards(
            git_diff=request.git_diff,
            rag_system=None,
            user_id=final_user_id,
            session_id=final_session_id
        )
        
        return {
            "status": "success",
            "result": result
        }
        
    except Exception as e:
        logger.error(f"简化代码规范检查失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"简化代码规范检查失败: {str(e)}")

@router.post("/extract-keywords")
@monitor_api_endpoint("code_review_extract_keywords")
async def extract_keywords(
    request: CodeReviewRequest,
    user_id: Optional[str] = Query(None, description="用户ID，用于追踪（URL参数）"),
    session_id: Optional[str] = Query(None, description="会话ID，用于追踪（URL参数）")
):
    """提取检索关键词"""
    try:
        logger.info(f"收到关键词提取请求，diff长度: {len(request.git_diff)}")
        
        # 优先使用请求体中的参数，如果没有则使用URL参数
        final_user_id = request.user_id or user_id
        final_session_id = request.session_id or session_id
        
        logger.info(f"追踪参数 - user_id: {final_user_id}, session_id: {final_session_id}")
        
        # 确保在创建RAG模型之前禁用Langfuse自动集成
        import os
        os.environ["LANGFUSE_OPENAI_INTEGRATION"] = "false"
        os.environ["LANGFUSE_AUTO_INSTRUMENT"] = "false"
        os.environ["OPENAI_LANGFUSE_PUBLIC_KEY"] = ""
        os.environ["OPENAI_LANGFUSE_SECRET_KEY"] = ""
        os.environ["OPENAI_LANGFUSE_HOST"] = ""
        
        # 创建RAG模型
        rag_model = RAGModel()
        
        # 提取关键词，传递追踪参数
        keywords = rag_model._extract_search_keywords(
            request.git_diff,
            user_id=final_user_id,
            session_id=final_session_id
        )
        
        return {
            "status": "success",
            "keywords": keywords,
            "diff_length": len(request.git_diff)
        }
        
    except Exception as e:
        logger.error(f"关键词提取失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"关键词提取失败: {str(e)}")

@router.get("/health")
async def health_check(
    user_id: Optional[str] = Query(None, description="用户ID，用于追踪"),
    session_id: Optional[str] = Query(None, description="会话ID，用于追踪")
):
    """健康检查 - GET请求使用URL参数"""
    logger.info(f"健康检查请求 - user_id: {user_id}, session_id: {session_id}")
    return {
        "status": "healthy",
        "service": "code_review",
        "version": "1.0.0",
        "tracking": {
            "user_id": user_id,
            "session_id": session_id
        }
    } 